<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor/dist/index.css" />
		<link rel="stylesheet" href="../css/addpost.css" />
		<script src="https://cdn.jsdelivr.net/npm/vditor/dist/index.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
		<script src="../js/mui.min.js"></script>
		<link href="../css/mui.min.css" rel="stylesheet" />
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">发帖</h1>
		</header>
		<div class="container">
			<form action="http://tcp.gykang.eu.org:8080/api/upload/post" method="POST" enctype="application/json"
				id="form">
				<label for="title">标题：</label>
				<input type="text" id="title" name="title" placeholder="请输入标题" required>
				<label for="content">内容：</label>
				<div id="content" name="content" placeholder="请输入内容" required></div>
				<label for="images">上传图片（最多9张）：</label>
				<div class="image-preview" id="image-preview">
					<div class="image-item add-image" id="add-image" onclick="triggerFileInput()">
						<span>+</span>
					</div>
				</div>
				<button type="submit" class="submit-btn" id="submitbtn">发布</button>
			</form>
		</div>
		<script>
			const maxImages = 9;
			let imageFiles = [];

			function addFilesToPreview(files) {
				const filesToAdd = Array.from(files).slice(0, maxImages - imageFiles.length);

				if (filesToAdd.length === 0) {
					mui.toast("最多只能上传9张图片！");
					return;
				}

				filesToAdd.forEach(file => {
					if (file.type.startsWith('image/')) {
						const reader = new FileReader();
						reader.onload = function(e) {
							const imageSrc = e.target.result;
							imageFiles.push({
								file: file,
								src: imageSrc
							});

							const imageItem = document.createElement('div');
							imageItem.classList.add('image-item');

							const img = document.createElement('img');
							img.src = imageSrc;
							imageItem.appendChild(img);

							const removeButton = document.createElement('div');
							removeButton.classList.add('remove');
							removeButton.textContent = '×';
							removeButton.onclick = () => removeImage(imageItem, imageFiles.length - 1);
							imageItem.appendChild(removeButton);

							document.getElementById('image-preview').insertBefore(imageItem, document.getElementById(
								'add-image'));

							updateAddImageButton();
						};
						reader.readAsDataURL(file);
					}
				});
			}

			// 删除图片
			function removeImage(imageItem, index) {
				imageFiles.splice(index, 1); // 从文件列表中删除该图片
				imageItem.remove(); // 从预览区域删除图片
				updateAddImageButton(); // 更新上传按钮
			}

			// 更新最后一个框显示" + "图标或上传框
			function updateAddImageButton() {
				const imagePreview = document.getElementById('image-preview');
				const addImageItem = document.getElementById('add-image');
				if (imageFiles.length >= maxImages) {
					addImageItem.style.display = 'none'; // 如果已上传9张，则隐藏" + "框
				} else {
					addImageItem.style.display = 'flex'; // 否则显示上传框
				}
			}

			// 点击选择文件上传
			function triggerFileInput() {
				const fileInput = document.createElement('input');
				fileInput.type = 'file';
				fileInput.accept = 'image/*';
				fileInput.multiple = true;
				fileInput.onchange = function() {
					addFilesToPreview(fileInput.files);
				};
				fileInput.click();
			}

			// 上传所有图片
			const form = document.getElementById('form'); // 确保这里的 form 是你表单的 id
			const submitbtn = document.getElementById('submitbtn'); // 按钮 id，不必改变

			// 给表单添加事件监听
			form.addEventListener("submit", function(event) {
				event.preventDefault(); // 阻止表单默认提交
				// 创建 FormData 对象
				const formData = new FormData();
				for (let i = 0; i < imageFiles.length; i++) {
					formData.append("imageFile[]", imageFiles[i]); // 确保字段名与后端一致
				}
				var contentText = document.getElementById('content').innerText;
				var title=document.getElementById('title').value;
				console.log("12345:",contentText,":54321:",title);


				// 创建并发送 XMLHttpRequest 请求
				var xhr = new XMLHttpRequest();
				xhr.open("POST", "http://tcp.gykang.eu.org:8080/api/upload/post", true);
				xhr.setRequestHeader("Content-Type", "application/json");

				// 处理响应
				xhr.onload = function() {
					if (xhr.status == 200) {
						mui.toast("上传成功");
						console.log("Response:", xhr.responseText); // 可选：查看返回的响应
					} else {
						mui.toast("上传失败. Status: " + xhr.status);
						console.error("Error:", xhr.status, xhr.statusText, xhr.responseText);
					}
				};

				// 发送请求
				xhr.onerror = function() {
					mui.toast("网络请求失败");
					console.error("Request failed: ", xhr.status, xhr.statusText);
				};
				const userID = localStorage.getItem('loginID');
				if (!userID) {
				    mui.toast('请登陆');
				    return;
				}
				mui.toast(userID);
				xhr.send(JSON.stringify({'userid':userID,'title':title,'contentText':contentText,'image':imageFiles})); // 发送 FormData
			});


			// 初始化 Vditor
			const vditor = new Vditor('content', {
				height: 300,
				cache: {
					enable: false
				},
				toolbar: [
					'emoji', 'undo', 'redo', 'bold', 'italic', 'strike', 'link', 'quote', 'list', 'ordered-list',
					'check', 'code', 'image', 'table', 'line', 'headings', 'outdent', 'indent', 'preview',
					'fullscreen'
				],
				preview: {
					delay: 500,
					mode: 'live',
				},
				editor: {
					theme: 'light',
					spellcheck: true,
					hotkey: {
						save: 'Ctrl+S'
					}
				},
				value: null,
			});
		</script>
	</body>
</html>